<template>
  <view class="memorial-container">
    <view class="empty-tip" v-if="displayMemorialData.length === 0">
      <image class="empty-icon" src="/static/data-empty.png" mode="aspectFit"></image>
      <text class="empty-text">暂无纪念日数据</text>
    </view>

    <view 
      class="memorial-card" 
      v-for="(item, index) in displayMemorialData" 
      :key="item.id"
      @tap="onMemorialClick(item)"
    >
      <view class="memorial-header">
        <uni-icons class="title-icon" :type="getIconType(item.title)" size="20" color="#B388FF"></uni-icons>
        <text class="memorial-title">{{ item.title }}</text>
        <uni-icons class="memorial-bell" type="notification" size="18" color="#999"></uni-icons>
      </view>
      
      <view class="memorial-content">
        <view class="date-info">
          <text class="date-text">{{ item.date }} {{ getWeekDay(item.date) }}</text>
          <text class="lunar-text" v-if="item.lunarDate">{{ item.lunarDate }}</text>
        </view>
        
        <view class="count-cards">
          <view class="count-card pink">
            <text class="count-label">倒计时</text>
            <text class="count-number">{{ item.countdown }}</text>
          </view>
          
          <view class="count-card purple">
            <text class="count-label">{{ item.anniversaryLabel || '周年' }}</text>
            <text class="count-number">{{ item.anniversary }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { defineProps, defineEmits, ref, onMounted, computed, watch } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import MemorialApi from '@/pages/contact/api/importday';

// 在 props 中添加 currentTab 和 tabIndex
const props = defineProps({
  memorialData: {
    type: Array,
    default: () => []
  },
  contactId: {
    type: String,
    default: ''
  },
  contactName: {
    type: String,
    default: ''
  },
  contactAvatar: {
    type: String,
    default: ''
  },
  currentTab: {
    type: Number,
    default: 0
  },
  tabIndex: {
    type: Number,
    default: 1
  }
});

const emit = defineEmits(['refresh', 'longpress']);

// 添加长按处理函数
const onLongPress = (item) => {
  emit('longpress', item, 'more');
};

// 添加本地纪念日数据
const localMemorialData = ref([]);
// 添加加载状态标记，防止重复加载
const isLoading = ref(false);
// 添加上次加载时间标记
const lastLoadTime = ref(0);

// 添加计算属性，判断当前tab是否激活
const isActive = computed(() => {
  return props.currentTab === props.tabIndex;
});

// 添加计算属性，优先使用本地数据
const displayMemorialData = computed(() => {
  return localMemorialData.value.length > 0 ? localMemorialData.value : props.memorialData;
});

// 添加加载纪念日数据的方法
const loadMemorialData = async () => {
  // 如果没有联系人ID或者正在加载，则不重复加载
  if (!props.contactId || isLoading.value) {
    console.log('纪念日tab 跳过加载 - contactId:', props.contactId, 'isLoading:', isLoading.value);
    return;
  }
  
  console.log('纪念日tab 开始加载数据 - contactId:', props.contactId);
  
  try {
    isLoading.value = true;
    
    const res = await MemorialApi.queryImportDays({
      contactId: parseInt(props.contactId)
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      // 转换API返回的数据格式为组件需要的格式
      localMemorialData.value = res.data.map(item => {
        // 计算倒计时天数
        const today = new Date();
        const importDate = new Date(item.importDate);
        const thisYearDate = new Date(today.getFullYear(), importDate.getMonth(), importDate.getDate());
        
        // 如果今年的日期已过，则计算到明年的日期
        if (thisYearDate < today) {
          thisYearDate.setFullYear(today.getFullYear() + 1);
        }
        
        const diffTime = thisYearDate.getTime() - today.getTime();
        const countdown = Math.ceil(diffTime / (1000 * 3600 * 24));
        
        // 计算周年数
        const years = today.getFullYear() - importDate.getFullYear();
        const anniversary = years > 0 ? `${years}周年` : '首年';
        
        // 格式化日期
        const formatDate = date => {
          const d = new Date(date);
          return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
        };
        
        return {
          id: item.id,
          title: item.dayName,
          date: formatDate(item.importDate),
          lunarDate: item.lunarDate || '', // 使用接口返回的农历日期
          description: item.remark || '',
          type: item.dayName.includes('生日') ? 'birthday' : 'memorial',
          countdown: countdown,
          anniversary: anniversary,
          anniversaryLabel: '周年'
        };
      });
      
      // 记录本次加载时间
      lastLoadTime.value = Date.now();
      
      console.log('纪念日tab 数据加载成功，共', localMemorialData.value.length, '条记录');
      
      // 通知父组件刷新完成
      emit('refresh');
    } else {
      localMemorialData.value = [];
      console.log('纪念日tab 数据加载失败:', res.msg);
      uni.showToast({
        title: res.msg || '获取纪念日列表失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取纪念日列表失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  } finally {
    isLoading.value = false;
  }
};

// 修改 onShow 生命周期钩子，确保每次显示时都能刷新数据
onShow(() => {
  console.log('纪念日tab onShow - currentTab:', props.currentTab, 'tabIndex:', props.tabIndex, 'isActive:', isActive.value);
  
  // 只有当组件真正显示（当前tab激活）且有联系人ID时才执行加载
  if (props.contactId && isActive.value) {
    console.log('纪念日tab 开始加载数据');
    loadMemorialData();
  } else {
    console.log('纪念日tab 不满足加载条件 - contactId:', props.contactId, 'isActive:', isActive.value);
  }
});

// 暴露方法给父组件调用
defineExpose({
  loadMemorialData
});


// 点击纪念日卡片，跳转到纪念日编辑页面
const onMemorialClick = (memorial) => {
  // 获取联系人信息
  const contactInfo = {
    id: props.contactId,
    name: props.contactName || '',
    img: props.contactAvatar || ''
  };
  
  uni.navigateTo({
    url: `/pages/contact/memorial-edit?id=${memorial.id}&contactId=${props.contactId}&mode=edit&contactName=${encodeURIComponent(contactInfo.name)}&contactImg=${encodeURIComponent(contactInfo.img)}`
  });
};


// 获取日期对应的星期几
const getWeekDay = (dateString) => {
  if (!dateString) return '';
  
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const date = new Date(dateString);
  
  if (isNaN(date.getTime())) return '';
  
  return weekDays[date.getDay()];
};

// 根据纪念日标题获取对应图标
const getIconType = (title) => {
  const iconMap = {
    '生日': 'gift',
    '结婚纪念日': 'heart',
    '入职纪念': 'medal'
  };
  
  return iconMap[title] || 'calendar';
};
</script>

<style lang="scss" scoped>
.memorial-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100%;
}

.memorial-card {
  margin-bottom: 20rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.memorial-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #f0f0f0;
}

.title-icon {
  margin-right: 10rpx;
}

.memorial-title {
  flex: 1;
  font-size: 16px;
  font-weight: 500;
  color: #B388FF; /* 修改标题颜色为紫色 */
}

.memorial-bell {
  padding: 6rpx;
}

.memorial-content {
  padding: 20rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-info {
  display: flex;
  flex-direction: column;
}

.date-text {
  font-size: 16px;
  color: #333;
  margin-bottom: 8rpx;
}

.lunar-text {
  font-size: 14px;
  color: #999;
  margin-top: 4rpx;
}

.count-cards {
  display: flex;
  gap: 16rpx;
}

.count-card {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.count-card.pink {
  background-color: #FF9E9E; /* 修改为更深的粉色 */
}

.count-card.purple {
  background-color: #B388FF; /* 修改为更深的紫色 */
}

.count-label {
  font-size: 12px;
  color: #fff; /* 修改标签文字颜色为白色 */
  margin-bottom: 8rpx;
}

.count-number {
  font-size: 18px;
  font-weight: 600;
  color: #fff; /* 修改数字颜色为白色 */
}

/* 空数据提示 */
.empty-tip {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>